<template>
  <div class="addform">
    <p style="font-size: 25px;font-weight: bold;text-align: center;">角色管理</p>
    <!-- 写表单 -->
    <el-form :model="roleObj">
      <el-form-item label="名称" label-width="80px">
        <el-input v-model="roleObj.name" />
      </el-form-item>
      <el-form-item label="选择继承角色" label-width="120px">
        <el-select v-model="roleObj.inheritedRoleId" @change="handleInheritRoleChange">
          <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资源" label-width="80px">
        <el-checkbox-group v-model="roleObj.resources">
          <el-checkbox v-for="resource in filteredResources" :key="resource.id" :label="resource.name"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-button type="primary" @click="addRole" style="margin-left: 200px;width:200px">添加</el-button>
    </el-form>

    <!-- 角色列表表格 -->
    <el-table :data="roles" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="inheritedRoleName" label="继承角色名称"></el-table-column>
      <el-table-column prop="resources" label="资源"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="editRole(row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteRole(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

let roleObj = ref({
  name: "",
  inheritedRoleId: "",
  resources: []
});
let roles = ref([]);
let resources = ref([]);

// 获取角色列表
const getRoles = () => {
  axios.get("http://127.0.0.1:8000/user/role/")
    .then(res => {
      roles.value = res.data.map(role => {
        const inheritedRoleName = role.inheritedRole ? role.inheritedRole.name : '无';
        const resourcesList = role.resources ? role.resources.map(res => res.resource_name).join(', ') : '无';
        return {
          ...role,
          inheritedRoleName,
          resources: resourcesList
        };
      });
    })
    .catch(error => {
      console.error("获取角色列表失败：", error);
    });
};

// 获取资源列表
const getResources = () => {
  axios.get("http://127.0.0.1:8000/user/ziyuan/")
    .then(res => {
      resources.value = res.data;
    })
    .catch(error => {
      console.error("获取资源列表失败：", error);
    });
};

// 处理继承角色变化
const handleInheritRoleChange = (roleId) => {
  if (!roleId) {
    roleObj.value.resources = [];
    resources.value = []; // 清空资源列表
  } else {
    axios.get(`http://127.0.0.1:8000/user/role/${roleId}/ziyuan/`)
      .then(res => {
        const resourceNames = res.data.map(item => item.resource_name); // 提取资源名称数组
        roleObj.value.resources = resourceNames; // 设置 roleObj.resources 为选中的资源名称数组
        resources.value = res.data.map(item => ({ id: item.id, name: item.resource_name })); // 更新 resources.value 为包含资源ID和名称的数组
      })
      .catch(error => {
        console.error("获取继承角色资源失败：", error);
      });
  }
};

// 添加角色
const addRole = () => {
  // 假设 roleObj.value.resources 包含的是资源名称，我们需要将它们转换为资源ID
  const resourcesIds = roleObj.value.resources.map(resourceName => {
    const resource = resources.value.find(r => r.name === resourceName);
    return resource ? resource.id : null;
  }).filter(id => id !== null && id !== ''); // 过滤掉未找到的资源和空字符串

  // 确保 resourcesIds 不包含空字符串
  const validResourcesIds = resourcesIds.filter(id => id !== '');

  const roleData = {
    name: roleObj.value.name,
    inheritedRoleId: roleObj.value.inheritedRoleId,
    resources: validResourcesIds.map(id => ({ resourceid_id: parseInt(id) })) // 发送资源ID对象数组，并确保转换为整数
  };

  axios.post("http://127.0.0.1:8000/user/roles/", roleData)
    .then(res => {
      console.log(res);
      ElMessage.success('添加成功');

      // 将新添加的角色添加到 roles 数组中
      const newRole = {
        id: res.data.id,
        name: res.data.name,
        inheritedRoleId: res.data.inheritedRoleId,
        resources: res.data.resources.map(r => r.resource_name).join(', '), // 将资源名称数组转换为字符串
        inheritedRoleName: res.data.inheritedRole ? res.data.inheritedRole.name : '无'
      };
      roles.value.push(newRole); // 将新角色添加到 roles 数组中

      roleObj.value = { name: "", inheritedRoleId: "", resources: [] }; // 重置表单
      console.log(roleObj.value);
      getRoles(); // 重新获取角色列表以更新表格
    })
    .catch(error => {
      console.error("添加角色失败：", error);
    });
};
// 添加角色
// const addRole = () => {
//   // 假设 roleObj.value.resources 包含的是资源名称，我们需要将它们转换为资源ID
//   const resourcesIds = roleObj.value.resources.map(resourceName => {
//     const resource = resources.value.find(r => r.name === resourceName);
//     return resource ? resource.id : null;
//   }).filter(id => id !== null); // 过滤掉未找到的资源
  
//   const roleData = {
//     name: roleObj.value.name,
//     inheritedRoleId: roleObj.value.inheritedRoleId,
//     resources: resourcesIds.map(id => ({ resourceid_id: id })) // 发送资源ID对象数组
//   };

//   axios.post("http://127.0.0.1:8000/user/roles/", roleData)
//     .then(res => {
//       console.log(res);
//       ElMessage.success('添加成功');

//       // 将新添加的角色添加到 roles 数组中
//       const newRole = {
//         id: res.data.id,
//         name: res.data.name,
//         inheritedRoleId: res.data.inheritedRoleId,
//         resources: res.data.resources.map(r => r.resource_name).join(', '), // 将资源名称数组转换为字符串
//         inheritedRoleName: res.data.inheritedRole ? res.data.inheritedRole.name : '无'
//       };
//       roles.value.push(newRole); // 将新角色添加到 roles 数组中

//       roleObj.value = { name: "", inheritedRoleId: "", resources: [] }; // 重置表单
//       console.log(roleObj.value);
//       getRoles(); // 重新获取角色列表以更新表格
//     })
//     .catch(error => {
//       console.error("添加角色失败：", error);
//     });
// };

// 删除角色
const deleteRole = (id) => { 
  axios.delete(`http://127.0.0.1:8000/user/roles/${id}/`)
  .then(res=>{
      alert("删除成功")
  })
  getRoles();

};

// 计算属性，用于过滤资源列表
const filteredResources = computed(() => {
  return roleObj.value.inheritedRoleId ? resources.value : [];
});

onMounted(() => {
  getRoles();
  getResources();
});
</script>